package com.java.controller;

import com.java.entity.User;
import com.java.service.AuthService;
import com.java.service.TokenService;
import com.java.util.JwtUtils;
import com.java.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class AuthController extends BaseController {

    @Autowired
    private AuthService authService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("auth/login")
    public ResultVo login(@RequestBody Map<String, Object> map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        User loginUser = authService.login(username, password);
        String token = JwtUtils.createToken(loginUser, 3600);
        // 将token存入redis
        tokenService.save(token);
        return ResultVo.success("登录成功", token);
    }

    @PostMapping("auth/verify")
    public ResultVo verify(@RequestBody String token) {
        boolean bb = tokenService.exists(token) && authService.verify(token);
        return toVo(bb);
    }

    @PostMapping("auth/logout")
    public ResultVo logout(@RequestBody String token) {
        tokenService.remove(token);
        return ResultVo.success("登出成功");
    }

}
